function [CopulaF,MarginQW]=DistApp_Hist_QW2CopulaF(UnitNumList,QW)

%% Preliminaries
UnitNumList =   UnitNumList(:)';
N_Dim       =   length(UnitNumList);
if N_Dim<=1
    error('Dimension has to be at least 1');
end
QW_Vec      =   full(QW(:));
QW_Mat      =   reshape(QW_Vec,UnitNumList);

%% Compute the Copula
% 1. Compute the CDF
MarginCDF   =   cell(N_Dim,1);
MarginQW    =   cell(N_Dim,1);
CDF_Mat     =   QW_Mat;
NzIndCell   =   cell(N_Dim,1);
NzNumList   =   zeros(1,N_Dim);
Tol         =   1e-7;%eps;
for ii=1:N_Dim
    MarginQW{ii}    =   DistApp_Hist_MergeQW2Marginal(UnitNumList,[ii],QW_Vec,'Vector');
    TempNzIdx       =   abs(MarginQW{ii})>Tol;
    NzNumList(ii)   =   sum(TempNzIdx);
    NzIndCell{ii}   =   find(TempNzIdx);
 
    MarginCDF{ii}   =   cumsum(MarginQW{ii});
    CDF_Mat         =   cumsum(CDF_Mat,ii);
end

% 2. Generate the Approximation Structure for Copula
% Note: 1) Remove the Grid Points which are too Close to the Adjecent one;
%       2) Add 0 to the left
if any(NzNumList<=0)
    error('There is a degenerated dimension');
end
TempIndCell =   cell(N_Dim,1);
MarginGrid  =   cell(N_Dim,1);
for ii=1:N_Dim
    MarginGrid{ii}  =   [0;MarginCDF{ii}(NzIndCell{ii})];
    TempIndCell{ii} =   1+(1:1:NzNumList(ii))';
end
Values      =   zeros(NzNumList+1);
Values(TempIndCell{:}) ...
            =   CDF_Mat(NzIndCell{:});

% 3. Compute the Copula
CopulaF     =   griddedInterpolant(MarginGrid,Values,'spline');